Add Binary

Given two binary strings, return their sum (also a binary string).
For example,a = "11",b = "1"
Return "100".

题目大意:实现二进制加法,字符串表示

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/28
 */
public class Solution {
    public String addBinary(String a, String b) {
        int len1 = a.length();
        int len2 = b.length();
        if (len1 == 0) return b;
        if (len2 == 0) return a;

        StringBuilder result = new StringBuilder();
        Boolean flag = false;
        char ch1, ch2;
        int tmp;
        while (len1 > 0 || len2 >0) {
            --len1;
            --len2;
            ch1 = len1 >= 0 ? a.charAt(len1) : '0';
            ch2 = len2 >= 0 ? b.charAt(len2) : '0';
            tmp = ch1 + ch2 - '0' * 2 + (flag ? 1 : 0);
            result.append((char)((tmp % 2) + '0'));
            flag = tmp/2 > 0;
        }
        if (flag) result.append('1');
        return String.valueOf(result.reverse());
    }
}
gzdaijie            updated 2016-05-28 23:37:59

results matching ""

    No results matching ""